//index.js
//获取应用实例
const app = getApp();
var codeV = {};
var openid = wx.getStorageSync('openid');
Page({
  data: {
    openid: openid,
    codeLabel: '获取验证码',
    tempCode: '',
    code: '',
    mobile: '',
    disabled: false, //验证码按钮禁用
    second: 60, //验证码的发送时间，倒计时
  },
  onLoad: function () { },
  //通用获取表单输入值
  changeInput(e) {
    let changed = {};
    let prop = e.currentTarget.dataset.prop
    changed[prop] = e.detail.value;
    this.setData(changed)
  },
  //点击获取验证码
  codeBtn: function (e) {
    var that = this;
    if (this.data.mobile.length != 11) {
      wx.showToast({
        title: '手机号格式错误',
        icon: 'none',
        duration: 1000
      });
      return true;
    }
    that.setData({
      disabled: true,
    })
    this.countDown();
  },
  //验证码倒计时
  countDown: function () {
    var that = this;
    codeV = setInterval(function () {
      that.setData({
        codeLabel: that.data.second - 1 + 's',
        second: that.data.second - 1,
        disabled: true,
      })
      //倒计时结束
      if (that.data.second == 0) {
        clearInterval(codeV)
        that.setData({
          codeLabel: '获取验证码',
          second: 60,
          disabled: false,
        })
      }
      //倒计时五秒的时候
      if (that.data.second == 55) {
        var str = Math.random().toString(36).slice(-8);
        that.setData({
          tempCode: str,
          code: str,
        })
      }
      //倒计时内容结束
    }, 1000)
  },
  /**
   * 提交按钮，绑定手机号
   */
  submitBtnTrue: function (e) {
    //登录状态
    openid = wx.getStorageSync('openid');
    var common = require('../../../utils/common.js');
    if (!openid) {
      common.getToLogin();
      return false;
    }
    var that = this;
    if (openid) {
      if (that.data.mobile == '' || that.data.code == '.') {
        wx.showToast({
          title: '内容不能为空',
          icon: 'none',
          duration: 1000
        });
        return false;
      }
      if (that.data.code != that.data.tempCode) {
        wx.showToast({
          title: '验证码错误',
          icon: 'none',
          duration: 1000
        });
        return false;
      }
    }
    wx.request({
      url: app.config.serverCfg.domain.myUserAdd,
      method: 'post',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: that.data,
      success: function (res) {
        wx.showToast({
          title: '绑定成功',
          icon: 'success',
          duration: 1000
        });
        clearInterval(codeV);
        that.setData({
          codeLabel: '获取验证码',
          second: 60,
          disabled: false,
          mobile: '',
          code: '',
          tempCode: '',
        })
      }
    });
  }
})